import ProTable, { ActionType } from "@ant-design/pro-table"
import { IconCategorySelector } from "./icon-category-selector"
import { useProTable } from "@sker/sdk"
import { Button, Card, Image, Input, Modal } from "antd"
import { SkerIcon } from "./sker-icon"
import { useModal } from "@sker/sdk"
import { useRef, useState } from "react"
import { SysIcon } from "@sker/model"
import { useModel } from "@sker/sdk"
import { CrudFilters } from "@refinedev/core"
import { useForm } from "@sker/sdk"
import { SkerUploadOne } from "./upload-one"
import { BetaSchemaForm } from "@ant-design/pro-form"
import { toWebUrl } from "@sker/sdk"
import { PlusOutlined } from "@ant-design/icons"

export const IconSelector: React.FC<{ onSelect: (keys: string) => void }> = ({ onSelect }) => {
    const { props: tableProps, selectedRowKeys, onChange } = useProTable('radio')
    const [category, setCategory] = useState<string[]>([])
    const icon = useModel(SysIcon)
    const [record, setRecord] = useState<any>()
    const { props: modalProps, setOpen, setTitle } = useModal('添加图标', () => setRecord(null))
    const actionRef = useRef<ActionType>()
    const uploadUrl = toWebUrl('imeepos/core/icon')
    const { props: formProps, form } = useForm([
        { title: '标题', dataIndex: 'svg_title' },
        { dataIndex: 'svg_name', fieldProps: { hidden: true }, formItemProps: { hidden: true } },
        { dataIndex: 'pre', fieldProps: { hidden: true }, formItemProps: { hidden: true } },
        { dataIndex: 'id', fieldProps: { hidden: true }, formItemProps: { hidden: true } },
        { dataIndex: 'svg_path', fieldProps: { hidden: true }, formItemProps: { hidden: true } },
        {
            title: '图标',
            renderFormItem(schema, config, form, action) {
                const id = form.getFieldValue('id')
                const svg_path = form.getFieldValue('svg_path')
                const svg_name = form.getFieldValue('svg_name')
                const fileList: any[] = [];
                if (id) {
                    fileList.push({
                        uid: id,
                        url: svg_path,
                        name: svg_name,
                    })
                }
                return <SkerUploadOne value={fileList} action={uploadUrl} onUpload={(values) => {
                    form.setFieldsValue(values)
                }} />
            },
        },
    ], async (values) => {
        if (record) {
            values.id = record.id;
        }
        await icon.save(values, ['id'])
        setOpen(false)
        actionRef.current?.reload();
        setRecord(null)
    })
    const toStr = (it: string) => it[0].toUpperCase() + it.slice(1)
    const toStrs = (it: string) => it.split('-').map(toStr).join('')
    onChange((keys) => {
        if (keys && keys.length > 0) {
            onSelect(toStrs(keys[0]))
        }
    })
    return <div className="flex">
        <div className="w-400px">
            <IconCategorySelector onSelect={e => {
                setCategory(e)
            }} />
        </div>
        <Card className="flex-1 ml-24px" title={'图标列表'} extra={<Button size={'small'} type={'primary'} icon={<PlusOutlined/>} onClick={e=>{
            setRecord(null)
            setOpen(true)
        }}></Button>}>
            <Modal {...modalProps}>
                <BetaSchemaForm {...formProps} />
            </Modal>
            <ProTable {...tableProps}
                params={{
                    category
                }}
                actionRef={actionRef}
                columns={[
                    { title: '序号', dataIndex: 'icon_id' },
                    { title: '名称', dataIndex: 'svg_title' },
                    {
                        title: '图标', dataIndex: 'svg_path', render(dom, entity, index, action, schema) {
                            return <Image width={'45px'} src={entity.svg_path} />
                        }
                    },
                ]}
                rowKey={record => `${record.pre}-${record.svg_name}`}
                request={async (params) => {
                    const filters: CrudFilters = [];
                    if (params.category && params.category.length > 0) {
                        filters.push({ field: 'pre', operator: 'in', value: params.category })
                    }
                    return icon.find([
                        'id', 'pre', 'icon_id', 'svg_title', 'svg_name', 'svg_path'
                    ], [
                        ...filters
                    ], [
                        { field: 'icon_id', order: 'desc' }
                    ], {
                        current: params.current,
                        pageSize: params.pageSize
                    })
                }} />
        </Card>
    </div>
}

export const IconSelectorButton: React.FC<{ value: string, onChange: (icon: string) => void }> = ({ value, onChange }) => {
    const { props, setOpen } = useModal('选择图标')
    const [icon, setIcon] = useState<string>(value)
    return <>
        <Modal {...props} width={'1200px'}>
            <IconSelector onSelect={e => {
                setIcon(e)
                onChange(e)
                setOpen(false)
            }} />
        </Modal>
        <Input readOnly aria-readonly={true} value={icon} style={{ cursor: 'pointer', backgroundColor: '#efefef' }} placeholder="请选择图标" onClick={e => setOpen(true)} addonAfter={<SkerIcon width={'24px'} height={`24px`} name={icon} />} />
    </>
}